'use strict';

const db = uniCloud.database();
const family = db.collection('family');
const users = db.collection('users');
exports.main = async (event, context) => {
	const {
		oldFamilyId,
		username
	} = event;

	// 从原家族中删除此成员
	const res = await family.where({ familyId: oldFamilyId }).get();
	console.log(res.data);
	let arr = res.data[0].members;
	arr = arr.filter(item => item !== username);
	await family.where({ familyId: oldFamilyId }).update({ members: arr });

	// 为此成员创建新的家族
	// 生成新的家族ID
	const newFamilyId = new Date().getTime().toString(36);
	const newFamily = await family.add({
		familyId: newFamilyId,
		name: username + '的家族',
		members: [
			username
		],
		cateList: []
	});

	//在users表中更新此成员的家族ID
	const res2 = await users.where({ username: username }).update({ familyId: newFamilyId });

	//返回数据给客户端
	return {
		code: 0,
		msg: '退出家族成功',
		// 返回username和新的familyId
		data: {
			username,
			familyId: newFamilyId
		}
	};
};